<template>
<section class="container">
    <div class="modal fade" id="ebayStoreDialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" @click="clearForm()" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">{{title}}</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="">
                <div class="form-group">
                  <div class="col-sm-12 flex">
                    <label for="" class="control-label min-width"><em class="sup">*</em>平台：</label>
                    <div class="inline-block">
                        {{platformName}}
                    </div>
                  </div>
                </div>
                <div class="form-group">
                  <div class="col-sm-12 flex">
                    <label for="" class="control-label min-width"><em class="sup">*</em>店铺名称：</label>
                    <div class="inline-block">
                      <input type="text" v-model="shopName" v-if="mode!='view'" class="form-control" placeholder="请输入自定义店铺名称">
                      <template v-else>{{shopName}}</template>
                    </div>
                  </div>
                </div>
                <div class="form-group">
                  <div class="col-sm-12 flex">
                    <label for="" class="control-label min-width"><em class="sup">*</em>发货仓库：</label>
                    <div class="inline-block">默认仓</div>
                  </div>
                </div>
                <div class="form-group" style="display:none;">
                  <div class="col-sm-12 flex">
                    <label for="" class="control-label min-width"><em class="sup">*</em>发货仓库：</label>
                    <div class="inline-block">
                      <select class="form-control" v-model="whId" v-if="mode!='view'">
                        <!--<option value="">请选择发货仓库</option>-->
                        <option v-for="(wareHose,index) in wareHoseSelectList" :key="index" v-bind:value="wareHose.id">
                          {{wareHose.name}}
                        </option>
                      </select>
                      <template v-else>
                        仓库
                      </template>
                    </div>
                  </div>
                </div>
                <div v-show="authorFlag">
                  <div class="form-group">
                    <div class="col-sm-12 flex">
                      <label for="" class="control-label min-width"><em class="sup">*</em>用户名：</label>
                      <div class="inline-block">
                        <input type="text" v-model="userName" class="form-control" v-if="mode!='view'" placeholder="请输入授权用户名">
                        <template v-else>{{userName}}</template>
                      </div>
                    </div>
                  </div>
                  <div class="form-group">
                    <div class="col-sm-12 flex">
                      <label for="" class="control-label min-width"><em class="sup">*</em>api Key：</label>
                      <div class="inline-block">
                        <input type="text" v-model="password" class="form-control" v-if="mode!='view'" placeholder="请输入授权密码">
                        <template v-else>xxxxxxx</template>
                      </div>
                    </div>
                  </div>
                  <div class="form-group">
                    <div class="col-sm-12 flex">
                      <label for="" class="control-label min-width" style="display: inline-block;height: 100px;"><em class="sup">*</em>授权url：</label>
                      <div class="inline-block">
                        <textarea v-model="apiUrl" class="form-control" v-if="mode!='view'"  style="resize:none;height: 100px;line-height: 25px;"  placeholder="请输入授权url"></textarea>
                        <template v-else>{{apiUrl}}</template>
                      </div>
                    </div>
                  </div>
                  <div class="form-group">
                    <div class="col-sm-12 flex">
                      <label for="" class="control-label min-width"><em class="sup">*</em>店铺id：</label>
                      <div class="inline-block">
                        <input type="text" v-model="storeId" class="form-control" v-if="mode!='view'" placeholder="请输入店铺id">
                        <template v-else>{{storeId}}</template>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="form-group">
                  <div class="col-sm-12 flex">
                    <label for="" class="control-label min-width"><em class="sup">*</em>站点域名：</label>
                    <div class="inline-block">
                      <!--<input type="text" v-model="webSite" v-if="mode!='view'" :disabled="ptId===1" class="form-control" placeholder="请输入站点域名">-->
                      <input type="hidden" v-model="webSite" v-if="ptId === 1" class="form-control" placeholder="请输入站点域名">
                      <input type="text" v-model="webSite" v-if="ptId != 1" :disabled="ptId===1" class="form-control" placeholder="请输入站点域名">
                      <template v-else>{{webSite}}</template>
                    </div>
                  </div>
                </div>
                <div class="form-group">
                  <div class="col-sm-12 flex" style="margin-bottom: 10px" v-if="ptId != 1 && mode != 'view'">
                    <label for="" class="control-label min-width"></label>
                    <div style="width: 100%;">
                     <el-button class="el-icon-plus myprimary" type="primary" size="small" style="float:right" @click="addPayType">新增收款方式</el-button>
                    </div>
                    </div>
                  <div class="col-sm-12 flex">

                    <div class="inline-block">
                      <table class="table table-bordered table-striped dataTable">
                        <thead>
                        <tr class="myThead">
                          <th>收款方式</th>
                          <th>收款账户</th>
                          <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="(accountItem,index) in accountList" >
                          <!-- <td style="text-align:right; width: 15%" >
                            <input type="checkbox" v-model="accountTypeIndex" :value="index">
                          </td> -->
                          <td style="text-align:right ;width: 101px">
                            {{accountItem.payment}}
                          </td>
                          <td>
                            <input type="text" class="form-control" v-if="mode!='view'" v-model="accountItem.account">
                          </td>
                          <td></td>
                        </tr>
                        <tr v-for="(accountItem,index) in customAccountList" :key="index">
                          <!-- <td style="text-align:right; width: 15%" >
                            <input type="checkbox" v-model="accountTypeIndex" :value="index">
                          </td> -->
                          <td style="text-align:left ;width: 101px">
                            <el-input v-model="accountItem.payment" v-if="mode!='view'"></el-input>
                            <template v-else>{{accountItem.payment}}</template>
                          </td>
                          <td>
                            <!-- <input type="text" class="form-control" v-model="accountItem.account"> -->
                            <el-input v-model="accountItem.account" v-if="mode!='view'"></el-input>
                            <template v-else>{{accountItem.account}}</template>
                          </td>
                          <td><i class="mydelete" @click="deletePayType(index)" v-if="mode!='view'"></i></td>
                        </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" @click="reauth" class="btn btn-primary"  v-if="mode=='edit' && ptId == 1" :disabled="statusoo !='2'">重新授权</button>
              <button type="button" class="btn btn-primary" v-if="mode!='view'" @click="getAuthorUrl()">保存</button>
            <button type="button" @click="clearForm()" class="btn btn-default" data-dismiss="modal">关闭</button>

          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>

    <div class="modal fade" style="z-index: 10000!important" id="accredit">
      <div class="modal-dialog" style="width: 400px!important">
        <div class="modal-content">
          <div class="modal-header" style="background: #FFF;">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">授权信息</h4>
          </div>
          <div class="modal-body">
            <p>{{message}}</p>
          </div>
          <div class="modal-footer">
          	<button type="button" class="btn btn-primary pull-left" data-dismiss="modal" @click="addShop()">是</button>
            <button type="button" class="btn btn-default " data-dismiss="modal">否</button>

          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
</section>
</template>
<script>
  import baseURL from '@/js/common/baseURL'
  import instance from '@/api/index.js'
  export default {
    name: "ebayStore",
    props: ["mode", "ptId", "id"],
    data() {
        return {
            platFormSelectList: [],
            // ptId: 1,
            shopName: "",
            wareHoseSelectList: [],
            customAccountList: [],
            userName: "",
            password: "",
            apiUrl: "",
            storeId: "",
            message: "",
            authorUrl: {
                url: '',
                sessionId: ''
            },
            token: "",

            // accountTypeIndex: [],//支付方式下标
            whId: this.value && this.value.whId || "",
            accountList: [],
            action: "auth",// auth  reauth
            statusoo:"",
            webSite: "",
        }
    },
    methods: {
        getPlatFormList: function () { //获取平台列表或者下拉框
            let vm = this;
            instance({
                method: 'post',
                url: '/v1/author/getPlatFrom',
            }).then(function (data) {
                vm.platFormList = data.data.data;
                vm.platFormSelectList = data.data.data;
            })
        },
        getPlayOutWareHoseList: function () { //获取发货仓下拉框
            let vm = this;
            // instance({
            //     method: 'post',
            //     url: '/v1/warehouse/getWareHouseNoPageList'
            // }).then(function (data) {
            //     vm.wareHoseSelectList = data.data.data;
            //     if(vm.wareHoseSelectList && vm.wareHoseSelectList.length > 0 && !vm.whId){
            //       console.log(vm.whId);
            //       vm.whId = vm.wareHoseSelectList[0].id
            //     }
            // })
          vm.wareHoseSelectList =[{name: "默认仓", id: "wh1535340237168"}]
          vm.whId = "wh1535340237168"
        },

        addPayType: function() {
            this.customAccountList.push({
                payment: "",
                account: "",
                payTypeId: 0,// 后端说可以随便填，自定义的统一置为0
            });
        },

        deletePayType: function(index) {
            this.customAccountList.splice(index, 1);
        },

        clearForm: function () { //清除提交表单，解除绑定
            let vm = this;
            vm.shopName = '';
            vm.ptId = '';
            vm.whId = '';
        },

      //获取授权url，和sessionId,并跳转入ebay授权
      getAuthorUrl: function () {
        let vm = this;
        if (!vm.validate(vm)) {
          return;
        }

        let param = {
            // id: vm.storeId,
            name: vm.shopName,
            ptId: vm.ptId,
            whId: vm.whId,
            webSite: vm.webSite,
            shopAccountList: vm.shopAccountList//[].concat(vm.shopAccountList).concat(vm.customAccountList)
        };
        if(vm.token) {
            param.token = vm.token;
        }
        if(this.mode === 'add') {// 新增
          instance({
            method: 'post',
            url: '/v1/author/getAuthUrl',
            data: param
          }).then(function (data) {
            if (data.data.data != null) {
              vm.authorUrl = data.data.data;
              //此方法会被浏览器拦截
              window.open(vm.authorUrl.url + vm.authorUrl.sessionId);
              vm.action = 'auth';
              $('#accredit').modal('show');
            } else {
              vm.alertMessage(data.data.success)
              $('#ebayStoreDialog').modal('hide');
              vm.$emit("commit");
            }

          });
        } else {// 编辑
          instance({
            method: 'post',
            url: '/v1/author/update/' + this.id,
            data: param
          }).then(function(data) {
            if(data.data.success) {
              vm.alertMessage("修改成功");
              $('#ebayStoreDialog').modal('hide');
              vm.$emit('commit');
            } else {
              vm.alertMessage("修改失败：" + data.data.message || "");
            }
          });
        }
      },
      reauth() {
        let vm = this;
        if (!vm.validate(vm)) {
          return;
        }

        let param = {
            // id: vm.storeId,
            name: vm.shopName,
            ptId: vm.ptId,
            whId: vm.whId,
            shopAccountList: vm.shopAccountList
        };
        if(vm.token) {
            param.token = vm.token;
        }
        // if(this.mode === 'add') {// 新增
          instance({
            method: 'post',
            url: '/v1/author/getAuthUrl',
            data: param
          }).then(function (data) {
            if (data.data.data != null) {
              vm.authorUrl = data.data.data;
              //此方法会被浏览器拦截
              window.open(vm.authorUrl.url + vm.authorUrl.sessionId);
              vm.action = 'reauth';
              $('#accredit').modal('show');
            } else {
              vm.alertMessage(data.data.success)
              $('#ebayStoreDialog').modal('hide');
              vm.$emit("commit");
            }
          });
        // }
      },

      validate: function (vm) {
        vm.shopAccountList = [];
        vm.token = "";
        let author =  {};
        if (!vm.shopName) {
          vm.$alert('请输入店铺名称！', '提示', {
            confirmButtonText: '确定',
          });
          return false;

        }
        console.log(vm.whId)
        if (!vm.whId) {
          vm.$alert('请选择发货仓库！', '提示', {
            confirmButtonText: '确定',
          });
          return false;
        }
        if (!vm.webSite) {
          vm.$alert('请输入站点域名！', '提示', {
            confirmButtonText: '确定',
          });
          return false;
        }else if(vm.webSite.length > 30){
          vm.$alert('站点域名字段值应该小于31位，请确认！', '提示', {
            confirmButtonText: '确定',
          });
          return false;
        }
        if (!vm.ptId) {
          vm.$alert('请授权平台！', '提示', {
            confirmButtonText: '确定',
          });
          return false;
        }else {
          if(vm.ptId == 3){
            if(vm.userName.trim() == ""){
                vm.$alert('请输入用户名', '提示', {
                  confirmButtonText: '确定',
                });
                return;
            }
            if(vm.password.trim() == ""){
                vm.$alert('请输入api Key', '提示', {
                  confirmButtonText: '确定',
                });
                return;
            }
            if(vm.apiUrl.trim() == ''){
                vm.$alert('请输入授权url', '提示', {
                  confirmButtonText: '确定',
                });
                return;
             }
            if(vm.apiUrl != '' && vm.apiUrl != null) {
              var match = /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?$/;
              if(!match.test(vm.apiUrl)){
                vm.$alert('请输入正确的授权url!', '提示', {
                  confirmButtonText: '确定',
                });
                return;
              }
            }
            if(vm.storeId.trim() == ""){
                vm.$alert('请输入店铺id', '提示', {
                  confirmButtonText: '确定',
                });
                return;
            }


            author.userName =vm.userName;
            author.password =vm.password;
            author.storeId =vm.storeId;
            author.apiUrl =vm.apiUrl;
            vm.token = JSON.stringify(author);
          }
        }

        vm.accountList.forEach((a)=>{
            if(a.account) {
                vm.shopAccountList.push({
                    payTypeId: a.code,
                    account: a.account,
                    id: a.id,
                    payment: a.payment
                });
            }
        });

        // let invalid = false;
        vm.customAccountList.forEach((c)=>{
            if(c.account && c.payment) {
                vm.shopAccountList.push({
                    payTypeId: c.payTypeId,
                    account: c.account,
                    id: c.id,
                    payment: c.payment
                });
            } /*else {
                invalid = true;
            }*/
        });

        if(vm.shopAccountList.length ==0) {
            vm.$alert('请输入收款账户！', '提示', {
              confirmButtonText: '确定',
            });
            return false;
        }

        return true;
      },
      // validateUrl:function(){ //正则表达式检查url
      //   let vm = this;
      //   var match = /^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?$/;
      //   if(!match.test(vm.apiUrl)){
      //     vm.apiUrl = '';
      //   }
      //   return;
      // },
      getPayTypeList: function () { //获取支付类型
        let vm = this;
        instance({
          method: 'get',
          url: '/v1/dict/payType/' + this.ptId,
        }).then(function (data) {
          if(vm.shopAccountList && vm.shopAccountList.length) {// 剥离accountList
            if(data.data.data && data.data.data.length) {
              data.data.data = data.data.data.map((x)=> {
                x.payment = x.codeValue;
                return x;
              });

              vm.accountList = data.data.data || [];

              vm.shopAccountList.forEach((a)=>{
                let t = vm.accountList.filter((x)=> {
                  // return x.payment == a.payment;
                  return x.code == a.payTypeId || x.payment == a.payment;
                });

                if(t[0]) {
                  t[0].account = a.account;
                  t[0].id = a.id;
                } else {
                  vm.customAccountList.push(a);
                }
              });
            } else {
              vm.customAccountList = data.data.data;
            }
          } else {
            vm.accountList = (data.data.data || []).map((x)=>{
              x.payment = x.codeValue;
              return x;
            });
          }
        })
      },

      addShop: function () {  //店铺授权并保存店铺
        let vm = this;
        if (!vm.validate(vm)) {
          return;
        }

        let param = {
            name: vm.shopName,
            ptId: vm.ptId,
            whId: vm.whId,
            shopAccountList: vm.shopAccountList
        };
        if(vm.token) {
            param.token = vm.token;
        }
        if(vm.action === 'auth') {
          instance({
            method: 'post',
            url: '/v1/author/addShop/' + vm.authorUrl.sessionId,
          //   data: vm.addShopForm
            data: param
          }).then(function (data) {
            let res = data.data;
            //如果是成功的弹窗告诉用户
            if (res.success) {
              vm.$alert('店铺授权成功！', '提示', {
                confirmButtonText: '确定',
              });
              vm.clearForm();
              $("#ebayStoreDialog").modal('hide');
              vm.$emit("commit");
            } else {
              vm.$alert('店铺授权失败！', '提示', {
                confirmButtonText: '确定',
              });
            }
          });
        } else {
          // 先保存
          instance({
            method: 'post',
            url: '/v1/author/update/' + this.id,
            data: param
          }).then(function(data) {
            if(data.data.success) {
              // vm.alertMessage("修改成功");
              // $('#ebayStoreDialog').modal('hide');
              // vm.$emit('commit');

              delete param.shopAccountList;
              param.id = vm.id;
              instance({
                method: 'post',
                url: '/v1/author/reAuthor/' + vm.authorUrl.sessionId,
                data: param
              }).then(function (data) {
                let res = data.data;
                //如果是成功的弹窗告诉用户
                if (res.success) {
                  vm.$alert('店铺授权成功！', '提示', {
                    confirmButtonText: '确定',
                  });
                  vm.clearForm();
                  $("#ebayStoreDialog").modal('hide');
                  vm.$emit("commit");
                } else {
                  vm.$alert('店铺授权失败！', '提示', {
                    confirmButtonText: '确定',
                  });
                }
              });
            } else {
              // vm.alertMessage("修改失败：" + data.data.message || "");
            }
          });
        }
      },

      alertMessage: function (value) {
        if (value) {
          this.$message({
            showClose: false,
            message: '操作成功!',
            type: 'success'
          });
        } else {
          this.$message({
            showClose: false,
            message: '操作失败!',
            type: 'error'
          });
        }
      },

      getStore() {
          this.statusoo=sessionStorage.getItem("statusoo")
          let vm = this;
          instance({
            method: 'post',
            url: '/v1/author/view/' + this.id,
          }).then(function (data) {
            vm.ptId = data.data.data.ptId;
            vm.shopName = data.data.data.name;
            vm.whId = data.data.data.whId;
            vm.shopAccountList = data.data.data.shopAccountList;
            vm.webSite = data.data.data.webSite;
            if(data.data.data.token && vm.ptId == 3) {
              /**
               * author.userName =vm.userName;
                author.password =vm.password;
                author.storeId =vm.storeId;
                author.apiUrl =vm.apiUrl;
               */
              let author = JSON.parse(data.data.data.token)
                vm.userName = author.userName;
                vm.password = author.password;
                vm.storeId = author.storeId;
                vm.apiUrl = author.apiUrl;
            }

            vm.getPayTypeList();
          });
        }
    },

    computed: {
        title() {
            let mapping = {
                "add": "授权店铺",
                "edit": "编辑店铺",
                "view": "店铺信息"
            };

            return mapping[this.mode || "view"];
        },

        platformName() {
            if(this.platFormSelectList && this.platFormSelectList.length) {
                let platform = this.platFormSelectList.filter((p)=> {
                    return p.id == this.ptId
                })[0];
                if(platform && this.ptId === 1){
                  this.webSite = platform.webSite;
                }
                return platform && platform.platformName || "";
            }

            return "";
        },

        authorFlag() {
            return this.ptId == 3;// 只有3才会输入授权的url账号等
        },


    },

    created() {
        this.getPlatFormList();
        this.getPlayOutWareHoseList();
        if(this.mode == "add") {
          this.getPayTypeList();
        } else {
          this.getStore();
        }
    }
}
</script>
<style scoped lang="less">
  //弹框
  .modal-dialog {
    width: 670px !important;
}
.modal-body {
    padding: 20px 30px !important;
}
.table{
  margin-top: 10px !important;;
}
.modal-dialog{
    border-radius: 4px;
    background: #fff;
    .modal-header{
        border-radius: 4px 4px 0 0;
        background: #fff !important;
        border-bottom-color: #E4E7ED;
    }
    .control-label {
      color: #606266;
      font-weight: normal;
      font-size: 14px;
    }
    .form-control{
        line-height: 40px;
        height: 40px;
        border-radius: 4px;
    }
    .box-header.with-border{
      border-radius: 4px 4px 0 0;
      border-bottom: 1px solid #E4E7ED;
    }
    .box-header{
      padding: 10px 10px 10px 0;
          margin: 0 20px;
       &::before{
            content: "";
            display: inline;
            height: 30px;
            width: 2px;
            background-color: #409EFF;
            position: absolute;
            left: -20px;
            top: 10px;
        }
        }
      .bg-info{
        background: none;
      }

    .box{
      border-top: none;
      box-shadow:none;
      border-radius: 4px;
      border: 1px solid #E4E7ED;
    }
        border-radius: 4px;

    .btn-primary:hover, .btn-primary:active, .btn-primary.hover{
      background: #409EFF;
    }
    .btn-primary{
       background: #409EFF;
       border-color: #409EFF;
       min-width: 68px;
       height: 40px;
       border-radius: 4px;

    }
    .pull-left{
    	float: inherit !importrent;
    }
    .myprimary{
          background: #fff;
          border: 1px solid #409EFF;
          color: #409EFF;
          padding: 13px 20px;
       }
      .myThead{
        height: 60px;
        line-height: 60px;
        background: #F5F7FA;
      }
    .box-body{
      padding-bottom: 0;
    }
    .modal-footer{
      border: none;
      text-align: center;
      padding-bottom: 40px;
      padding-left: 84px;
    }
    .modal-footer .btn-default{
       min-width: 68px;
       height: 40px;
    }
  }
  .text-red {
    color: #FF5655!important;
}
.control-label{
  position: relative;
}
.sup{
      margin-right: 3px;
      color: #FF5655;
}
  .mydelete{
        display: inline-block;
        width: 18px;
        height: 18px;
        margin:  0 12px;
        background:url('../../assets/img/myDelete.png') no-repeat;
        background-size: 100%;

}

</style>
